<template>
	<view>
		<view class="addfile uni-row uni-row-wrap">
			<view class="apply-image" v-for="(imageSrc, index) in imageList" :key="index" :style="{
				border: move && currentIndex == index ? '1px dashed #eeeeee;' : 'none',
				width: imageSize + 'px',
				height: imageSize + 'px'
			}">
				<image class="image" mode="aspectFill" 
					:style="{ width: imageSize + 'px', height: imageSize + 'px' }" 
					:id="`image_${index}`"
					:src="imageSrc" 
					@touchstart="(e: TouchEvent) => onTouchStart(e, index)" 
					@touchmove="onTouchMove" 
					@touchend="onTouchEnd"
				></image>
			</view>
			<view class="uni-addfile uni-row uni-center" id="image_10" :style="{ width: imageSize+ 'px', height: imageSize+ 'px' }" @click="chooseImage" v-if="imageList.length < count">			
				<image class="plus" src="./plus.png" mode="scaleToFill"></image>			
			</view>
		</view>
		<view class="delete-area uni-row uni-column uni-center" ref="deleteArea" :class="{show: move, opacity: isInDeleteArea}" :style="safeBottomStyle">
			<uni-icons type="trash" size="26" color="#fff"></uni-icons>
			<text class="font-14 color-white">{{ isInDeleteArea ? '松手即可删除' : '删除' }}</text>
		</view>
	</view>
</template>
 
<script lang="uts"> 
	/**
	 * 图片9宫格拖拽删除
	 * 注意：页面暂不支持滚动，滚动可能导致布局错乱 
	 */
    import { ImgUrlPrefix } from '@/utils/util.js'
	import FileChoose from '@/uni_modules/file-choose/components/file-choose/file-choose.vue'
	export default {
		components:{
			FileChoose
		},
		props: {
			imageList: {
				type: Array,
				default: []
			},
			count: {
				type: Number,
				default: 9
			},
			file_config:{
				type: Object,
				default: {}
			}
		},
		data() {
			return {
				currentElement: null,
				currentIndex: 0,
				move: false,
				lastX: 0,
				lastY: 0, 
				
				// 图片起始y轴高度
				startY: 0,
				
				// 记录当前拖拽节点的原始位置
				nodePosition: [] as number[],
				bottomSafeHeight: 0,
				
				// 删除区域
				deleteAreaElement: null,
				deleteAreaY: 0,
				deleteTimer: -1,
				isInDeleteArea: false,
				
				// 每张图片的尺寸，宽和高保持一致
				imageSize: 90,
				// 自定义样式
				imageStyle: []
			}
		},
		computed: {
			safeBottomStyle() : string {
				return `height: 100px;padding-bottom: ${this.bottomSafeHeight}px`;
			}
		},
		watch: {
			imageList: {
				handler() {
					this.$nextTick(() => this.resetImagesPosition());
				},
				deep: true
			}
		},
		mounted() {
			const sys = uni.getSystemInfoSync();
			this.bottomSafeHeight = sys.safeAreaInsets.bottom;
			this.deleteAreaElement = this.$refs['deleteArea'];
			
			// https://doc.dcloud.net.cn/uni-app-x/vue/#lifecycle-options
			// 计算图片起始区域
			uni.createSelectorQuery().in(this).select('.addfile').boundingClientRect().exec((ret) => {
				console.log('ret',ret)
				const nodeInfo = ret[0];
				this.startY = nodeInfo.top!; 
			});
			
			// 计算删除区域的y轴位置, 
			if (this.deleteAreaY == 0) {
				this.deleteAreaY = sys.screenHeight - (100 + this.bottomSafeHeight);
			}
			
			// 计算每张图片的尺寸，左边边距各位30px，每张图片之间间距5px
			if (this.imageSize == 90) {
				// #ifdef APP-ANDROID
				this.imageSize = (((sys.windowWidth) - 75) / 3).toInt(); 
				// #endif
				
				// #ifdef APP-IOS
				this.imageSize = ((sys.windowWidth) - 75) / 3;
				// #endif
			}
		},
		methods: {
			onTouchStart(e : TouchEvent, index: number) {
				const element = e.target || null;
				if (element == null) return;
				
				this.currentElement = element;
				console.log(element,'onTouchStart')
				this.nodePosition = [element.offsetLeft, element.offsetTop];
				this.currentIndex = index;
				if (!this.move) {
					this.move = true;
				}
			},
			
			onTouchMove(e : TouchEvent) {
				e.preventDefault()
				let p = e.touches[0]
				if (p.screenX == this.lastX && p.screenY == this.lastY) {
					return
				}
				this.lastX = p.screenX
				this.lastY = p.screenY
				this.imageMovingAction(p.screenX, p.screenY);
			},
			
			onTouchEnd(e : TouchEvent) {
				if (e.touches.length == 0) {
					this.move = false;
					this.deleteImage();
				}
			},
			
			imageMovingAction(x: number, y: number) {
				const imageHalfSize = this.imageSize / 2;
				this.currentElement?.style?.setProperty('position', 'fixed');
				this.currentElement?.style?.setProperty('left', x - imageHalfSize + 'px');
				this.currentElement?.style?.setProperty('top', y - imageHalfSize + 'px');
				this.currentElement?.style?.setProperty('z-index', 1 + this.currentIndex);
				this.currentElement?.style?.setProperty('opacity', 0.8);
				// 判断当前y轴是否触碰到了删除区域
				if (this.deleteAreaY > 0) {
					this.isInDeleteArea = y + imageHalfSize >= this.deleteAreaY;
				}
			},
			
			// 移动结束重置图片位置
			imageMovendAction() {
				this.currentElement?.style?.setProperty('left', this.nodePosition[0] + 'px')
				this.currentElement?.style?.setProperty('top', this.nodePosition[1] + 'px')
				this.currentElement?.style?.setProperty('z-index', 1);
				this.currentElement?.style?.setProperty('opacity', 1); 
				this.resetImagesPosition(); // 重置所有图片位置
			},
			
			deleteImage() {
				if (!this.isInDeleteArea) {
					this.imageMovendAction();
					return;
				}
				this.isInDeleteArea = false;
				this.imageList.splice(this.currentIndex, 1);
			},
			
			// 获取剩余的所有节点信息，并重置图片位置 
			resetImagesPosition() {
				const spacing = 5; // 图片间的间隔
				const startX = 30; // x轴起始边距
				const staerY = this.startY; // y轴起始边距
				for (let i = 0; i < this.imageList.length; i++) {
				    const row = Math.floor(i / 3); // 计算行数
				    const col = i % 3; // 计算列数
				    const x = startX + col * (this.imageSize + spacing); // 计算 x 轴坐标
				    const y = staerY + row * (this.imageSize + spacing); // 计算 y 轴坐标
					this.setImagePosition(i, x, y);
				}
			},
			
			// 设置图片位置
			setImagePosition(index, x, y) {
				console.log(index, x, y,'drag-image')
				// const element = uni.getElementById(`image_${index}`);
				// element?.style?.setProperty('position', 'fixed');
				// element?.style?.setProperty('left', x + 'px'); 
				// element?.style?.setProperty('top', y + 'px');
				// this.imageStyle[index] = {
				// 	id: `image_${index}`,
				// 	position: 'fixed',
				// 	left: x +'px',
				// 	top: y + 'px'
				// }
			},
			
			// 选择图片
			chooseImage () {
				this.$emit('chooseImage', {});
			},
			chooseImage2(val) {
				console.log('val999999',val)
				this.$emit('chooseImage2', {data: JSON.stringify(val)});
			},
			
			// 图片地址拼接
			getImgUrl(val) {
				const url = ImgUrlPrefix(val)
				return url
			},
		}
	}
</script>

<style scoped lang="scss">
	.addfile {
		margin-bottom: 60rpx;
		.apply-image {
			margin: 0 10rpx 10rpx 0;
			min-width: 180rpx;
			min-height: 180rpx;
		}
		
		.uni-addfile, .image {
			background-color: #eee;
			width: 100%;
			height: 100%;
			border-radius: 6rpx;
			
			.plus {
				width: 80rpx;
				height: 80rpx;
			}
		}
	}
	
	// 删除区域
	.delete-area {
		background: #fa5151;
		position: fixed;
		bottom: -220rpx;
		left: 0;
		right: 0;
		z-index: 99;
		transition-property: bottom;
		transition-duration: 300ms;
	}
	
	.delete-area.show {
		bottom: 0;
	}
	
	.delete-area.opacity {
		background: rgba(250, 81, 81, 0.6);
	}
</style>